package com.fanglei.demo.aop;

import com.alibaba.fastjson.JSONObject;
import com.fanglei.demo.core.dto.resp.BaseResp;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * controller层日志切面，实现功能
 * before requset信息打印，ip....,
 *
 * @Auther: dengqi
 * @Date: 2018/8/2 11:02
 * @Description:
 */
@Aspect
@Component
@Slf4j
public class ControllerLog {

    @Pointcut("execution(* com.fanglei.demo.controller.*.*(..))")
    public void contrLog(){}

//    @Before("contrLog()")
//    public void doBefore(){
//        log.info("before method");
//    }
//
//    @After("contrLog()")
//    public void doAfter(){
//        log.info("after method");
//    }
//
//    @AfterReturning("contrLog()")
//    public void afterReturning(){
//        log.info("after returning");
//    }

    @Around("contrLog()")
    public Object around(ProceedingJoinPoint point){
        log.info("--------around log start -------");
        long startTime = System.currentTimeMillis();
        boolean flag  = true;
        String apiName = "default";
        try {
            Object[] args = point.getArgs();
            log.info("request info : {}", JSONObject.toJSONString(args));
            Object o = point.proceed();
            log.info("resp info : {}", JSONObject.toJSONString(o));
            return  o;
        } catch (Throwable throwable) {
            flag = false;
            log.info("error:",throwable);
            BaseResp resp = new BaseResp(BaseResp.ApiCodeEnum.ERROR);
            return resp;
        }finally {
            log.info("--------apiName :{} end ,costTime:{},success:{}-------",apiName,System.currentTimeMillis()-startTime,flag);
        }

    }

    @AfterThrowing(value = "contrLog()",throwing = "exe")
    public void afterThrowing(){
        log.info("after throwing ex");
    }

}
